package controllers;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import models.ObjetivoCarga;
import models.Usuario;
import controllers.CRUD.ObjectType;
import controllers.securesocial.SecureSocial;
import play.db.Model;
import play.exceptions.TemplateNotFoundException;
import play.mvc.*;

@With(SecureSocial.class)
public class ObjetivoCargas extends CustomCRUD {
	
	private static final int PREFIJO_PROPERTY_OBJETIVO = 14;

	public static void list(int page, String search, String searchFields, String orderBy, String order) {

		if(orderBy != null){
			orderBy = orderBy.substring(PREFIJO_PROPERTY_OBJETIVO);
		}
		
		Usuario user = Usuario.find("bySocialUserId", session.get("securesocial.user")).first();

		Long userId = user.id;

		ObjectType type = ObjectType.get(getControllerClass());
		notFoundIfNull(type);

		if (page < 1) {
			page = 1;
		}

		List<Model> objects = type.findPage(page, search, searchFields, orderBy, order, (String) request.args.get("where"));

		List<Model> filteredObjects = new ArrayList<Model>();

		for (Model model : objects) {
			if (((ObjetivoCarga) model).getUsuario().id.equals(userId)) {
				filteredObjects.add(model);
			}
		}

		objects = filteredObjects;

		Long count = new Long(objects.size());
		Long totalCount = new Long(objects.size());

		try {
			render(type, objects, count, totalCount, page, orderBy, order, userId);
		} catch (TemplateNotFoundException e) {
			render(getControllerName() + "/list.html", type, objects, count, totalCount, page, orderBy, order, userId);
		}
	}

	public static void newObjetivoCarga(Long userId) throws Exception {

		ObjectType type = ObjectType.get(getControllerClass());

		notFoundIfNull(type);

		render(getControllerName() + "/newObjetivoCarga.html", type, userId);
	}

	public static void addObjetivoCarga(Long userId, Double pesoActual, String fecha) throws Exception {

		ObjetivoCarga o = new ObjetivoCarga();

		Usuario usuario = Usuario.find("bySocialUserId", session.get("securesocial.user")).first();
		o.setUsuario(usuario);

		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
		java.util.Date fechaActual = sdf.parse(fecha);
		o.setFechaActual(fechaActual);

		o.setPesoActual(pesoActual);

		o.save();

		list(0, null, null, null, null);
	}

	public static void show(String id) throws Exception {

		ObjectType type = ObjectType.get(getControllerClass());
		notFoundIfNull(type);

		ObjetivoCarga object = (ObjetivoCarga) type.findById(id);

		notFoundIfNull(object);

		try {
			render(type, object);
		} catch (TemplateNotFoundException e) {
			render(getControllerName() + "/show.html", type, object);
		}
	}
}
